﻿Imports System.IO
Imports System.Web.UI.WebControls

Namespace DotNetNuke.Modules.ActiveForums
    Partial Public Class uploader
        Inherits AMPageBase

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                Dim uc As New UserController
                Dim ui As User = uc.GetUser(PortalSettings.PortalId, -1)
                Dim fc As New ForumController
                Dim fi As Forum = fc.Forums_Get(CInt(Request.Params("ForumId")), ui.UserId, True)

                If Not fi Is Nothing Then
                    If Permissions.HasPerm(fi.Security.Attach, ui.UserRoles) Then
                        If inpFile.HasFile Then
                            Dim sFile As String = String.Empty
                            Dim sExt As String = String.Empty
                            Dim maxImgHeight As Integer = fi.AttachMaxHeight
                            Dim maxImgWidth As Integer = fi.AttachMaxWidth
                            Dim contentType As String = inpFile.PostedFile.ContentType
                            sFile = Path.GetFileName(inpFile.PostedFile.FileName).Replace(" ", "_")

                            sExt = Path.GetExtension(sFile)
                            If sFile.Length >= 250 Then
                                sFile = sFile.Replace(sExt, String.Empty)
                                sFile = sFile.Substring(0, (250 - sExt.Length))
                                sFile = sFile & sExt
                            End If
                            sExt = sExt.Replace(".", String.Empty)
                            If Not fi.AttachTypeAllowed.ToString.ToLower.Contains(sExt.ToLower) Then
                                Response.Write("<script type=""text/javascript"">window.top.af_setMessage('" & Utilities.GetSharedResource("[RESX:Error:BlockedFile]") & "');</script>")
                                Exit Sub
                            End If
                            If fi.AttachMaxSize > 0 Then
                                If (inpFile.PostedFile.ContentLength / 1024) > fi.AttachMaxSize Then
                                    Response.Write("<script type=""text/javascript"">window.top.af_setMessage('" & String.Format(Utilities.GetSharedResource("[RESX:Error:FileTooLarge]"), fi.AttachMaxSize) & "');</script>")
                                    Exit Sub
                                End If
                            End If

                            Dim inpStream As Stream = inpFile.PostedFile.InputStream
                            Dim imgStream As New MemoryStream
                            Dim useMemStream As Boolean = False
                            Dim allowDownload As Boolean = True
                            Dim displayInline As Boolean = False
                            If sExt.ToLower = "jpg" Or sExt.ToLower = "gif" Or sExt.ToLower = "bmp" Or sExt.ToLower = "png" Or sExt.ToLower = "jpeg" Then
                                useMemStream = True
                                imgStream = CType(Images.CreateImageForDB(inpStream, maxImgHeight, maxImgWidth), MemoryStream)
                                contentType = "image/x-png"
                                allowDownload = False
                                displayInline = True
                            End If

                            Dim ac As New Data.AttachController
                            Dim ai As New AttachInfo
                            ai.ContentId = -1
                            ai.UserID = ui.UserId

                            ai.ContentType = contentType
                            ai.DisplayInline = displayInline
                            ai.AllowDownload = allowDownload
                            ai.ParentAttachId = 0
                            If fi.AttachStore = AttachStores.DATABASE Then
                                If useMemStream Then
                                    ai.FileSize = CInt(imgStream.Length)
                                    ai.FileData = imgStream.ToArray
                                Else

                                    Dim byteData(CInt(inpStream.Length - 1)) As Byte
                                    inpStream.Read(byteData, 0, CInt(inpStream.Length))
                                    ai.FileSize = CInt(inpStream.Length)
                                    ai.FileData = byteData
                                End If
                                ai.Filename = sFile
                            Else
                                If useMemStream Then
                                    ai.FileSize = CInt(imgStream.Length)
                                    ai.Filename = SaveToFile(imgStream, sFile)
                                Else
                                    Dim byteData(CInt(inpStream.Length)) As Byte
                                    inpStream.Read(byteData, 0, CInt(inpStream.Length))
                                    ai.FileSize = CInt(inpStream.Length)
                                    ai.Filename = SaveToFile(inpFile, sFile)
                                End If

                            End If
                            Dim attachId As Integer = ac.Attach_Save(ai)
                            Response.Write("<script type=""text/javascript"">window.top.af_isUploaded(" & attachId.ToString & ");</script>")
                        End If
                    Else
                        inpFile.Visible = False
                    End If
                Else
                    inpFile.Visible = False
                End If
            Catch ex As Exception
                Response.Write("<script type=""text/javascript"">window.top.af_setMessage('" & ex.Message & "');</script>")
            End Try

        End Sub
        Private Function SaveToFile(ByVal sFile As MemoryStream, ByVal Filename As String) As String
            Dim strPath As String
            strPath = Request.MapPath(PortalSettings.HomeDirectory & "activeforums_Attach")
            If Not (Directory.Exists(strPath)) Then
                Directory.CreateDirectory(strPath)
            End If
            Dim i As Integer = 0
            Dim sFullFile As String = strPath & "\" & Filename
            Dim tmpFileName As String = Filename
            While File.Exists(sFullFile)
                i += 1
                Filename = i.ToString.PadLeft(3, CChar("0")) & "_" & tmpFileName
                sFullFile = strPath & "\" & Filename
            End While
            Dim fs As FileStream = File.OpenWrite(sFullFile)
            fs.Write(sFile.GetBuffer(), 0, CInt(sFile.Position))
            fs.Close()
            Return Filename
        End Function

        Private Function SaveToFile(ByVal inpFile As FileUpload, ByVal Filename As String) As String
            Dim strPath As String
            strPath = Request.MapPath(PortalSettings.HomeDirectory & "activeforums_Attach")
            If Not (Directory.Exists(strPath)) Then
                Directory.CreateDirectory(strPath)
            End If
            Dim i As Integer = 0
            Dim sFullFile As String = strPath & "\" & Filename
            While File.Exists(sFullFile)
                i += 1
                Filename = i.ToString.PadLeft(3, CChar("0")) & "_" & Filename
                sFullFile = strPath & "\" & Filename
            End While
            inpFile.PostedFile.SaveAs(sFullFile)
            Return Filename
        End Function
    End Class
End Namespace
